<template>
  <view class="third-pay">
    <view class="pay-header">
      <view class="header-price">￥{{info.totalPayment}}</view>
			<countdown-timer :time="info.expireSecond*1000" :autoStart="true" @finish='handleBack'>
				<template v-slot="{hour, minute, second}">
					<h2>支付倒计时: <span style="margin-left: 20rpx;" class="span">{{hour>9?hour:'0'+hour}}</span>:<span class="span">{{minute>9?minute:'0'+minute}}</span>:<span class="span">{{second>9?second:'0'+second}}</span></h2>      
				</template>
			</countdown-timer>
    </view>
    <h2 class="pay-h2">请选择支付方式</h2>
    <view class="pay-list">
      <view class="list-item" v-if="curPay == 0">
        <!-- <image src="@/static/weixin-icon.png" class="item-img"></image> -->
        微信
        <!-- <image src="@/static/yuan.png" class="item-icon"></image> -->
      </view>
      <view class="list-item" v-if="curPay == 1">
        <!-- <image src="@/static/douyin.png" class="item-img"></image> -->
        抖音
        <!-- <image src="@/static/yuan.png" class="item-icon"></image> -->
      </view>
    </view>
    <view class="pay-button" @click="handlePay">确认支付 ￥{{info.totalPayment}}</view>
  </view>
</template>

<script>
  import countdownTimer from '@/components/countdown-timer.vue'
  export default {
    components:{countdownTimer},
    data() {
      return {
        curPay:0,
        oid:'',
        info:{},
        url:'',
        fromFlag:'',
        channel:''
      }
    },
    onLoad() {
      // #ifdef MP-TOUTIAO
      this.curPay = 1
      // #endif
      const routes = getCurrentPages()
      const params = routes[routes.length - 1].options
      console.log(params,'params----------------')
      let url = decodeURIComponent(params.url)
      this.fromFlag = decodeURIComponent(params.fromFlag)
      const token = uni.getStorageSync('token')
      if(token){
        url = decodeURIComponent(params.url + `${decodeURIComponent(params.url).includes('?')?'&':'?'}token=${token}&channel=${this.$channel}`)
      }
      this.url = url
      uni.showLoading({
        title:'加载中...'
      })
      let headers = {}
      if(params.channel){
        headers = {channel:params.channel}
      }
      this.channel = params.channel || this.$channel
      const oid = params.id || params.orderId
      this.oid = oid
      this.$get(`/order/users/orders/detail?orderId=${oid}`,'','1',headers).then(res=>{
        if(res.code == '1'){
          this.info = res.content
          if((res.content.totalPayment*1) > 0){
            setTimeout(()=>{
              this.handlePay()
            },500)
          }else{
            if(this.fromFlag == 'orderCenter' || this.channel.includes('app')){
              uni.redirectTo({
                url:'/minePackage/order-list'
              })
              return;
            }
            uni.redirectTo({
              url:'/minePackage/order-list'
            })
          }
        }else{
          uni.showToast({
            title: res.message,
            icon:'nonee'
          })
        }
      })
    },
    methods: {
      handleBack(){ ///  返回
        const src = `${this.BASE_URL == 'https://api.tuan.ues.xyz'?'https://order.ant.shop':'https://sit.order.ant.shop'}/#/orderSubPack/order/index?tab=0&sassAppid=${this.$sassAppId}&channel=${this.channel}&token=${uni.getStorageSync('token')}`
        uni.redirectTo({
          url:`/pages/fineEngine/webView?url=${encodeURIComponent(src)}`
        })
      },
      getOpenId(){
        return new Promise(resolve => {
          if(uni.getStorageSync('openID')){
            resolve(uni.getStorageSync('openID'))
          }else{
            // #ifdef H5
            resolve(uni.getStorageSync('openID'))
            // #endif
            // #ifdef MP-WEIXIN
            uni.login({
              scopes:'auth_base',
              onlyAuthorize:false,
              success:res=>{
                this.$post('/yahe/login',{
                  loginType:'WECHAT',
                  username: uni.getAccountInfoSync().miniProgram.appId,
                  password:res.code
                }).then(res=>{
                  if(res.code === '1'){
                    uni.setStorageSync('openID',res.content.openId)
                    resolve(res.content.openId)
                  }
                })
              }
            })
            // #endif
            // #ifdef MP-TOUTIAO
            uni.login({
              scopes:'auth_base',
              onlyAuthorize:false,
              success:res=>{
                this.$post('/yahe/login',{
                  loginType:'DOUYIN',
                  username: this.$mpAppid,
                  password:res.code
                }).then(res=>{
                  if(res.code === '1'){
                    uni.setStorageSync('openID',res.content.openId)
                    resolve(res.content.openId)
                  }
                })
              }
            })
            // #endif
          }
        })
      },
      async handlePay(){    /// 点击去支付
        uni.showLoading({
          title:'加载中...'
        })
        const data = {
          appId:this.$mpAppid,
          openId:await this.getOpenId(),
          orderId:this.oid
        }
        const ret = await this.$post('/order/users/orders/pay',data,'1')
        if(ret.code == '1'){
          let {content} = ret
          if(this.curPay == 0){
            uni.requestPayment({
              timeStamp: content.timeStamp,
              nonceStr: content.nonceStr,
              package: content.package,
              signType: content.signType,
              paySign: content.paySign,
              success:res=>{
                this.handlePaySuccess(data)
              },
              fail:err=>{
                uni.showToast({
                  title:'支付失败',
                  icon:'none'
                })
              }
            })
          }else{
            tt.pay({
              orderInfo: {
                order_id:content.data.orderId,
                order_token: content.data.orderToken
              },
              service: 5,
              _debug:1,
              success:res=>{
                if(res.code == 0){
                  this.handlePaySuccess(data)
                }
              },
              fail:err=>{
                uni.showToast({
                  title:'支付失败',
                  icon:'none'
                })
              }
            });
          }
        }else{
          uni.showToast({
            title:ret.message,
            icon:'none'
          })
        }
      },
      handlePaySuccess(data){  ///  支付成功
        if(this.fromFlag == 'orderCenter' || this.channel.includes('app')){
            uni.redirectTo({
              url:'/minePackage/order-list'
            })
          return;
        }
        uni.redirectTo({
          url:'/minePackage/order-list'
        })
      },
    }
  }
</script>

<style lang="less" scoped>
.third-pay{
  min-height: 100vh;
  background: #f0eef3;
}
.third-pay .pay-header{
  background:#fff;
  font-size:24rpx;
  color:#aaa;
  text-align:center;
  padding: 40rpx 0;
  .span{
    padding:0 4rpx;
    background: #f96b27;
    color: #fff;
    border-radius: 8rpx;
  }
}
.pay-h2{
  font-weight: 400;
  font-size: 30rpx;
  padding: 30rpx 24rpx;
}

.third-pay .pay-header .header-price{
  font-size: 50rpx;
  color: #111;
  margin-bottom: 6rpx;
  font-weight: bold;
}

.third-pay .pay-header .header-price .price-span{
  color:#f96b27;
  margin-left: 10rpx;
  font-weight: 500;
}

.third-pay .pay-list{
  background:#fff;
}

.third-pay .pay-list .list-item{
  display:flex;
  align-items:center;
  padding: 24rpx;
  font-size: 30rpx;
}
.third-pay .pay-list .disabled{
  color:#aaa;
}
.third-pay .pay-list .list-item .h2-span{
  font-size:24rpx;
}
.third-pay .pay-list .list-item .item-img{
  width: 60rpx;
  height: 60rpx;
  margin-right: 30rpx;
}
.third-pay .pay-list .list-item .item-icon{
  width: 30rpx;
  height: 30rpx;
  margin-left: auto;
}

.third-pay .pay-button{
  background:#f96b27;
  color:#fff;
  line-height: 90rpx;
  margin: 50rpx 24rpx;
  text-align:center;
  border-radius:80rpx;
  font-weight: 500;
}


</style>
